<template>
  <div class="main">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="角色标识" prop="roleKey">
          <el-input
            v-model="searchForm.roleKey"
            placeholder="请输入角色标识"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>角色列表</h3>
        </div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            新增角色
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRoles.length"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 角色表格 -->
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="roleList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="roleKey" label="角色标识" width="150" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column
          prop="description"
          label="描述"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleStatusType(row.status) as any">
              {{ formatRoleStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="用户数量" width="100">
          <template #default="{ row }">
            {{ row.userCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleViewPermissions(row)"
            >
              权限
            </el-button>
            <el-button
              :type="row.status === '0' ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === "0" ? "停用" : "启用" }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              :disabled="!canDeleteRole(row)"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色编辑对话框 -->
    <RoleEditDialog
      v-model:visible="editDialogVisible"
      :role-info="currentRole"
      @success="handleEditSuccess"
    />

    <!-- 角色权限管理对话框 -->
    <RolePermissionDialog
      v-model:visible="permissionDialogVisible"
      :role-info="currentRole"
      @success="handlePermissionSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import { RoleEditDialog, RolePermissionDialog } from "./components";
import {
  getRoleListApi,
  deleteRoleApi,
  batchDeleteRolesApi,
  updateRoleStatusApi,
  RoleManagementUtils,
  type RoleInfo,
  type RoleListParams
} from "@/api/role-management";

defineOptions({
  name: "SystemRole"
});

// 响应式数据
const loading = ref(false);
const roleList = ref<RoleInfo[]>([]);
const selectedRoles = ref<RoleInfo[]>([]);
const currentRole = ref<RoleInfo | null>(null);
const editDialogVisible = ref(false);
const permissionDialogVisible = ref(false);

// 搜索表单
const searchForm = reactive<RoleListParams>({
  roleKey: "",
  roleName: "",
  status: ""
});

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 表单引用
const searchFormRef = ref();
const tableRef = ref();

// 工具函数
const formatRoleStatus = RoleManagementUtils.formatRoleStatus;
const getRoleStatusType = RoleManagementUtils.getRoleStatusType;
const canDeleteRole = RoleManagementUtils.canDeleteRole;

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN");
};

/**
 * 加载角色列表
 */
const loadRoleList = async () => {
  try {
    loading.value = true;
    const params: RoleListParams = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    };

    // 过滤空值
    Object.keys(params).forEach(key => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });

    const response = await getRoleListApi(params);
    if (response.code === 200 && response.data) {
      roleList.value = response.data.records || [];
      pagination.total = response.data.total || 0;
      pagination.current = response.data.current || 1;
      pagination.size = response.data.size || 10;
    } else {
      ElMessage.error(response.message || "获取角色列表失败");
    }
  } catch (error) {
    console.error("加载角色列表失败:", error);
    ElMessage.error("获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 搜索处理
 */
const handleSearch = () => {
  pagination.current = 1;
  loadRoleList();
};

/**
 * 重置搜索
 */
const handleReset = () => {
  searchFormRef.value?.resetFields();
  Object.assign(searchForm, {
    roleKey: "",
    roleName: "",
    status: ""
  });
  pagination.current = 1;
  loadRoleList();
};

/**
 * 表格选择变化
 */
const handleSelectionChange = (selection: RoleInfo[]) => {
  selectedRoles.value = selection;
};

/**
 * 分页大小变化
 */
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadRoleList();
};

/**
 * 当前页变化
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current;
  loadRoleList();
};

/**
 * 新增角色
 */
const handleAdd = () => {
  currentRole.value = null;
  editDialogVisible.value = true;
};

/**
 * 编辑角色
 */
const handleEdit = (role: RoleInfo) => {
  currentRole.value = role;
  editDialogVisible.value = true;
};

/**
 * 查看角色权限
 */
const handleViewPermissions = (role: RoleInfo) => {
  currentRole.value = role;
  permissionDialogVisible.value = true;
};

/**
 * 切换角色状态
 */
const handleToggleStatus = async (role: RoleInfo) => {
  const newStatus = role.status === "0" ? "1" : "0";
  const statusText = newStatus === "0" ? "启用" : "停用";

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}角色"${role.roleName}"吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await updateRoleStatusApi(role.id, newStatus);
    if (response.code === 200) {
      ElMessage.success(`角色${statusText}成功`);
      loadRoleList();
    } else {
      ElMessage.error(response.message || `角色${statusText}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("切换角色状态失败:", error);
      ElMessage.error(`角色${statusText}失败`);
    }
  }
};

/**
 * 删除角色
 */
const handleDelete = async (role: RoleInfo) => {
  if (!canDeleteRole(role)) {
    ElMessage.warning("该角色不能删除");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${role.roleName}"吗？此操作不可恢复！`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await deleteRoleApi(role.id);
    if (response.code === 200) {
      ElMessage.success("角色删除成功");
      loadRoleList();
    } else {
      ElMessage.error(response.message || "角色删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除角色失败:", error);
      ElMessage.error("角色删除失败");
    }
  }
};

/**
 * 批量删除角色
 */
const handleBatchDelete = async () => {
  if (!selectedRoles.value.length) {
    ElMessage.warning("请选择要删除的角色");
    return;
  }

  // 检查是否有不能删除的角色
  const cannotDeleteRoles = selectedRoles.value.filter(
    role => !canDeleteRole(role)
  );
  if (cannotDeleteRoles.length > 0) {
    const roleNames = cannotDeleteRoles.map(role => role.roleName).join("、");
    ElMessage.warning(`以下角色不能删除：${roleNames}`);
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？此操作不可恢复！`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const roleIds = selectedRoles.value.map(role => role.id);
    const response = await batchDeleteRolesApi(roleIds);
    if (response.code === 200) {
      ElMessage.success("角色批量删除成功");
      selectedRoles.value = [];
      loadRoleList();
    } else {
      ElMessage.error(response.message || "角色批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除角色失败:", error);
      ElMessage.error("角色批量删除失败");
    }
  }
};

/**
 * 编辑成功回调
 */
const handleEditSuccess = () => {
  loadRoleList();
};

/**
 * 权限管理成功回调
 */
const handlePermissionSuccess = () => {
  loadRoleList();
};

// 组件挂载时加载数据
onMounted(() => {
  loadRoleList();
});
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .main {
    padding: 0;
  }

  .search-form {
    :deep(.el-form-item) {
      width: 100%;
      margin-bottom: 10px;

      .el-form-item__label {
        width: 70px !important;
        padding-right: 8px;
        text-align: left;
      }

      .el-input,
      .el-select {
        width: 100% !important;
      }
    }
  }

  .table-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch !important;

    .table-actions {
      justify-content: center;
    }
  }
}

.main {
  padding: 0;
}

.search-card {
  margin-bottom: 20px;

  .search-form {
    margin-bottom: 0;

    :deep(.el-form-item) {
      margin-bottom: 0;

      .el-form-item__label {
        width: 80px !important;
        padding-right: 12px;
        font-weight: 600;
        color: #303133;
        text-align: right;
      }
    }
  }
}

.table-card {
  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .table-title {
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .table-actions {
      display: flex;
      gap: 10px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}

// 表格样式优化
:deep(.el-table) {
  .el-table__header {
    th {
      font-weight: 600;
      color: #606266;
      background-color: #fafafa;
    }
  }

  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}

// 按钮样式优化
.el-button {
  &.mr-1 {
    margin-right: 4px;
  }
}
</style>
